import api from '@/api/index'
import tool from '../../utils/tool'
import { ElMessage } from 'element-plus'
import userRoutes from '@/config/route';

export default {
	state: {
		// 用户信息
		userInfo: null,
    // 导航菜单
		menuList: [],
	},
	mutations: {
		SET_USERINFO: (state, user) => {
			state.userInfo = user
		},
    SET_MENULIST: (state, list) => {
			state.menuList = list
		},
    LOGOUT: (state) => {
			state.menuList = []
			state.userInfo = null
		},
	},
	actions: {
    // 登录
		login({ commit }, data){
      return new Promise((resolve, reject) => {
        api.auth.token.post(data).then(res => {
          if(res.access_token){
            tool.data.set("TOKEN", res.access_token)
						
						tool.data.set("USER_INFO", res) 
						// tool.cookie.set("TOKEN");
          }
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    logOut ({ commit }) {
      return new Promise(resolve => {
        tool.data.remove('TOKEN')
        tool.data.clear()
        commit('LOGOUT')
        resolve()
      })
    },
    // 用户信息
		getInfo({ commit }) {
			return new Promise((resolve, reject) => {
				let info = tool.data.get("USER_INFO")
				if(info) {
					commit('SET_USERINFO', info)
					resolve(info)
				}
				
			})
		},
    // 菜单权限
		getAuthMenu({ commit }) {
			return new Promise((resolve, reject) => {
			
						// 合并静态页面为菜单的项
						let staticList = userRoutes.filter(item => {
							return item.menuType == 'C'
						})
						let allMenu = [...staticList]
						commit('SET_MENULIST', allMenu)
						tool.data.set("MENU", allMenu)
						// tool.data.set("PERMISSIONS", res.data.permissions)
						tool.data.set("DASHBOARDGRID", [])
						resolve()
				// api.auth.getLoginMenu.get().then(res=> {
				// 	if(res.code == 200) {
				// 		if(res.data.length == 0){
				// 			ElMessage({
				// 				message: '当前用户无任何菜单权限，请联系系统管理员", "无权限访问',
				// 				type: 'error',
				// 			})
				// 			return
				// 		}
						
				// 	}
				// }).catch(err => {
				// 	reject(err)
				// })
			})
		},
	}
}
